package com.baixiaowen.xiaoaointerview.并发基础篇;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier 练习
 *
 *      模拟查询1000w个订单，然后在并行查询每个订单对应的产品和发货单
 *
 * @author Baixiaowen
 */
public class CyclicBarrierTest {

    CyclicBarrier barrier;
    int page = 0;

    public CyclicBarrierTest() {

        barrier = new CyclicBarrier(2, () -> {
            System.err.println("sync...");
            page ++;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }

    // 准备产品
    void prepareProducts(){
        while (page < 1000) {
            try {
                System.err.println("fetch product...");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    // 准备发货单
    void prepareDeliveryOrders() {
        while (page < 1000) {
            try {
                System.err.println("fetch delivery order...");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    void run() {
        new Thread(this::prepareProducts).start();
        new Thread(this::prepareDeliveryOrders).start();
    }

    public static void main(String[] args) {
        CyclicBarrierTest test = new CyclicBarrierTest();
        test.run();
    }
}
